package cn.edu.hznu.coursework.service;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import cn.edu.hznu.coursework.entity.Student;
import cn.edu.hznu.coursework.entity.Teacher;
import cn.edu.hznu.coursework.repository.StudentRepository;
import cn.edu.hznu.coursework.repository.TeacherRepository;

@Service("SignService")
@Transactional(rollbackFor = {Exception.class})
public class SignServiceImpl implements SignService{
	
	@Autowired
	private StudentRepository studentRepo;
	
	@Autowired
	private TeacherRepository teacherRepo;

	@Override
	public Student studentLogin(String studentNo, String password) {
		Student savedStudent = studentRepo.findByNo(studentNo);
		if(null != savedStudent && password.equals(savedStudent.getPassword())){
			return savedStudent;
		}else{
			return null;
		}
	}

	@Override
	public Teacher teacherLogin(String studentNo, String password) {
		Teacher savedTeacher = teacherRepo.findByNo(studentNo);
		if(null != savedTeacher && password.equals(savedTeacher.getPassword())){
			return savedTeacher;
		}else{
			return null;
		}
	}

	@Override
	public void studentRegister(Student student) throws Exception {
		if(null != studentRepo.findByNo(student.getNo())){
//			throw new Exception("student already exists.");
			throw new Exception("该学生已经存在.");
		}
		try{
			studentRepo.save(student);
		}catch(Exception ex){
			throw ex;
		}
	}

	@Override
	public void teacherRegister(Teacher teacher) throws Exception {
		if(null != teacherRepo.findByNo(teacher.getNo())){
//			throw new Exception("teacher already exists.");
			throw new Exception("该教师已经存在.");
		}
		try{
			teacherRepo.save(teacher);
		}catch(Exception ex){
			throw ex;
		}
	}
	
}
